﻿using AiXiu.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AiXiu.DAL
{
    public class LoginDAL
    {
        AiXiuDbContext dbContext = new AiXiuDbContext();
        /// <summary>
        /// 通过用户名登录
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public TBLogins getUserByName(string userName)
        {
            TBLogins user = dbContext.TBLogins.FirstOrDefault(a => a.UserName == userName);
            return user;
        }
        /// <summary>
        /// 通过手机号码登录
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public TBLogins getUserByPhone(string Phone)
        {
            TBLogins user2 = dbContext.TBLogins.FirstOrDefault(a => a.MobileNumber == Phone);
            return user2;
        }
        /// <summary>
        /// 判断用户名是否已注册
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public bool ExistsUserName(string userName)
        {
            return dbContext.TBLogins.Any(a => a.UserName == userName);
        }
        /// <summary>
        /// 判断手机号是否已注册
        /// </summary>
        /// <param name="Phone"></param>
        /// <returns></returns>
        public bool ExistsUserPhone(string Phone)
        {
            return dbContext.TBLogins.Any(a => a.MobileNumber == Phone);
        }

        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="login">登录信息</param>
        /// <returns>返回用户Id</returns>
        public int Register(TBLogins login)
        {
            // 准备存储过程参数
            SqlParameter[] sqlParams = {
                new SqlParameter("@userName", login.UserName),
                new SqlParameter("@mobileNumber", login.MobileNumber),
                new SqlParameter("@password", login.Password),
                new SqlParameter("@userId", SqlDbType.Int)
            };
            sqlParams[3].Direction = ParameterDirection.Output;
            // 初始化数据库命令
            DbCommand cmd = dbContext.Database.Connection.CreateCommand();
            cmd.CommandText = "proc_adduser";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddRange(sqlParams);
            // 执行存储过程
            if (cmd.Connection.State != ConnectionState.Open)
            {
                cmd.Connection.Open();
            }
            cmd.ExecuteNonQuery();
            if (cmd.Connection.State == ConnectionState.Open)
            {
                cmd.Connection.Close();
            }
            // 返回结果
            return int.Parse(sqlParams[3].Value.ToString());
        }
    }
}
